(function () {
    "use strict";
    angular.module('panels', ['Tab', 'commons', 'userSettings'])
        .config(function ($sceProvider) {
            // Completely disable SCE.  For demonstration purposes only!
            // Do not use in new projects.
            $sceProvider.enabled(false);
        })
        .directive('panelContainer', function ($http, urlPrefix, LoginInfo, Promise, loadConf) {
            return {
                scope: {},
                link: function (scope) {
                    scope.isArray = angular.isArray;
                    Promise.all({
                        loginInfo: LoginInfo,
                        settings: loadConf('panel-container.yml')
                    }).then(function (results) {
                        var loginInfo = results.loginInfo,
                            settings = results.settings,
                            roles = {};
                        angular.forEach(loginInfo.currentUser.roles, function (role) {
                            roles[role.ROLE_ID] = true;
                        }, roles);
                        angular.element.each(settings, function (roleId, v) {
                            if (roles[roleId]) {
                                scope.panels = settings[roleId];
                                return false; // break;
                            }
                        });
                        if (!scope.panels) {
                            scope.panels = settings['default'];
                            if (!scope.panels) {
                                alert('没有您的首页设置，请联系管理员！');
                            }
                        }
                    });
                },
                replace: true,
                templateUrl: 'app/panel/container.html'
            };
        }).directive('moreLink', function (tabService) {
        return {
            scope: {
                moreLink: '='
            },
            link: function (scope, elem) {
                scope.tabService = tabService;
                elem.on('click', function () {
                    var tabName = elem.parent().text().trim().split(/\s/)[0];
                    tabService.addTab({name: tabName, url: scope.moreLink});
                });
            },
            transclude: true,
            template: '<span ng-transclude></span>'
        };
    });
}());